//
//  PersonalDataVC.m
//  phmall
//
//  Created by admin on 2017/11/7.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "PersonalDataVC.h"
#import "PersonalDataCell.h"
#import "AccountSecurityVC.h"

#import "ChangePasswordViewController.h"
#import "ZLPhotoActionSheet.h"
#import "ZLCustomCamera.h"
@interface PersonalDataVC ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableview;
@property(nonatomic,strong)NSMutableArray *titles;

@property(nonatomic,strong)MBProgressHUD *hud;

@end

@implementation PersonalDataVC
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navBarBgAlpha=@"1.0";
    // 改变NavBar顶层View的颜色
    self.navigationController.navigationBar.barTintColor =  [UIColor whiteColor];
}
- (void)loadDataWithInfo{
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"member_index/get_member_info"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            [self analysisDataWithMemberInfoDictionary:response[@"data"][0]];
        }else{
//            [PublicClass ProgressHUDModeText:@"账号未登录或登录已过期" andTime:2];
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        [self.hud hideAnimated:YES];
    }];
}
- (void)loadDataWithEditInfo:(NSString *)value andKey:(NSString *)key{
    self.hud =[MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    self.hud.detailsLabel.text = Localized(@"加载中...");
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"member_data/edit"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:key forKey:@"key"];
    [parametersDic setObject:value forKey:@"val"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            [self loadDataWithInfo];
        }else{
//            [PublicClass ProgressHUDModeText:@"账号未登录或登录已过期" andTime:2];
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
        }
        [self.hud hideAnimated:YES];
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        [self.hud hideAnimated:YES];
    }];
}
- (void)analysisDataWithMemberInfoDictionary:(NSDictionary*)dictionary{
    self.model = [UserInfoModel yy_modelWithDictionary:dictionary];

    YYCache *cache = [YYCache cacheWithName:@"user"];
    [cache setObject:dictionary forKey:@"userInfo"];
    
    [self.tableview reloadData];
}
-(void)imageUp:(UIImage *)image{
    self.hud =[MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    self.hud.detailsLabel.text =  Localized(@"加载中...");
    // －－－－－－－－－－－－－－－－－－－－－－－－－－－－上传图片－－－－
    /*
     此段代码如果需要修改，可以调整的位置
     1. 把upload.php改成网站开发人员告知的地址
     2. 把name改成网站开发人员告知的字段名
     */
    // 查询条件
    NSString *domainStr=[NSString stringWithFormat:@"%@%@",HomeURL,@"upload/logo_upload"];

    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:@"1" forKey:@"ios"];
    // 基于AFN3.0+ 封装的HTPPSession句柄
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 15;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    // 在parameters里存放照片以外的对象
    [manager POST:domainStr parameters:parametersDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData  *imageData = UIImageJPEGRepresentation(image, 0.5);
        // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
        // 要解决此问题，
        // 可以在上传时使用当前的系统事件作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        [formatter setDateFormat:@"yyyyMMddHHmmss"];
        NSString *dateString = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
        /*
         *该方法的参数
         1. appendPartWithFileData：要上传的照片[二进制流]
         2. name：对应网站上[upload.php中]处理文件的字段（比如upload）
         3. fileName：要保存在服务器上的文件名
         4. mimeType：上传的文件的类型
         */
        [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"thumbnail"] fileName:fileName mimeType:@"image/jpeg"]; //
        //            }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"---上传进度--- %@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableDictionary *obj=responseObject;
        NSMutableDictionary *data=obj[@"data"];
        //        NSMutableDictionary *userData=data[@"data"];
        if ([obj[@"ret"] isEqualToString:@"200"]) {
            if ([data[@"status"] isEqualToString:@"1"]) {
                NSLog(@"```上传成功``` %@",responseObject);
                [self loadDataWithInfo];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"xxx上传失败xxx %@", error);
        [self.hud hideAnimated:YES];
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    self.navigationItem.leftBarButtonItem=leftBar;

    [self.view addSubview:self.tableview];
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view).priorityHigh();
        make.bottom.equalTo(self.view).with.offset(-49-self.tabBar_height).priorityHigh();
    }];
    
    UIButton* logOut=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:logOut];
    [logOut setTitle:Localized(@"退出登录") forState:UIControlStateNormal];
    [logOut addTarget:self action:@selector(logOutAction) forControlEvents:UIControlEventTouchUpInside];
    [logOut setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    logOut.backgroundColor=[UIColor orangeColor];
//    [logOut setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
    [logOut mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(49);
        make.bottom.equalTo(self.view).offset(-self.tabBar_height);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view.mas_right);
    }];
    

    // Do any additional setup after loading the view.
}

-(void)logOutAction{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"确定要退出登录吗？") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击取消");
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"退出") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
        NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"login/login_out"];
        NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
        
        [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
         
            [PublicClass ProgressHUDModeText:Localized(@"退出成功") andTime:2];
            [self userLogout];
            [self.navigationController.tabBarController setSelectedIndex:0];
            [self.navigationController popViewControllerAnimated:NO];
        } andFailure:^{
           [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
        }];
    }]];
    
    [self.navigationController presentViewController:alertController animated:YES completion:nil];
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0&&indexPath.row==0) {
        return 60;
    }else{
        return 44;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.titles.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if (self.model==nil) {
//        return 0;
//    }
    NSMutableArray *title=self.titles[section];
    return title.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PersonalDataCell *cell=[PersonalDataCell theShareCellWithTableView:tableView];
    cell.opaque=YES;
    cell.layer.drawsAsynchronously=YES;
    cell.layer.rasterizationScale=[UIScreen mainScreen].scale;
    NSMutableArray *title=self.titles[indexPath.section];
    cell.title.text=title[indexPath.row];
    
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    cell.img.hidden=NO;
                    [cell.img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@union/images/%@",IMGURL,self.model.member_image]] placeholderImage:[UIImage imageNamed:@"图片空白页"]];
                    break;
                case 1:
                    cell.img.hidden=YES;
                    cell.message.text=self.model.member_id;
                    break;
                case 2:
                    cell.img.hidden=YES;
                    if ([self.model.member_sex isEqualToString:@"1"]){
                        cell.message.text=Localized(@"男");
                    }else{
                        cell.message.text=Localized(@"女");
                    }
                    break;
                case 3:
                    cell.img.hidden=YES;
                    cell.message.text=[self timeWithTimeIntervalString:self.model.member_birthday];
                    break;
                default:
                    break;
            }
            break;
        case 1:
            cell.img.hidden=YES;
            switch (indexPath.row) {
                case 0:

                    break;
                default:
                    break;
            }
            break;
    }

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    [self selectedPortrait];
                    break;
                case 1:

                    break;
                case 2:
                    [self sexSelection];
                    break;
                case 3:
                    
                    break;
                default:
                    break;
            }
            break;
        case 1:
            switch (indexPath.row) {
                case 0:
                    [self accountSecurity];
                    break;
                default:
                    break;
            }
            break;
        default:
            break;
    }
}
-(void)selectedPortrait{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photograph];
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self showWithPreview];
    }]];
    [self.navigationController presentViewController:alertController animated:YES completion:nil];
}
- (void)showWithPreview{
    [[self getPas] showPhotoLibrary];
}
- (ZLPhotoActionSheet *)getPas
{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    
#pragma mark - 参数配置 optional，可直接使用 defaultPhotoConfiguration
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = YES;
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = YES;
    //设置照片最大预览数
    actionSheet.configuration.maxPreviewCount = 10;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    //设置允许选择的视频最大时长
    actionSheet.configuration.maxVideoDuration = 10;
    //设置照片cell弧度
    actionSheet.configuration.cellCornerRadio = 0;
    //单选模式是否显示选择按钮
    //    actionSheet.configuration.showSelectBtn = YES;
    //是否在选择图片后直接进入编辑界面
    actionSheet.configuration.editAfterSelectThumbnailImage = NO;
    //设置编辑比例
    //    actionSheet.configuration.clipRatios = @[GetClipRatio(7, 1)];
    //是否在已选择照片上显示遮罩层
    actionSheet.configuration.showSelectedMask = NO;
    //颜色，状态栏样式
    actionSheet.configuration.selectedMaskColor = [UIColor redColor];
    actionSheet.configuration.navBarColor = [UIColor whiteColor];
    actionSheet.configuration.navTitleColor = [UIColor blackColor];
    actionSheet.configuration.bottomBtnsNormalTitleColor =  [UIColor blackColor];
    actionSheet.configuration.bottomBtnsDisableBgColor =  [UIColor blackColor];
    actionSheet.configuration.bottomViewBgColor = [UIColor whiteColor];
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //是否允许框架解析图片
    actionSheet.configuration.shouldAnialysisAsset = YES;
    //框架语言
    //    actionSheet.configuration.languageType = self.languageSegment.selectedSegmentIndex;
    //是否使用系统相机
    //    actionSheet.configuration.useSystemCamera = YES;
    //    actionSheet.configuration.sessionPreset = ZLCaptureSessionPreset1920x1080;
    //    actionSheet.configuration.exportVideoType = ZLExportVideoTypeMp4;
    
#pragma mark - required
    //如果调用的方法没有传sender，则该属性必须提前赋值
    actionSheet.sender = self;
    //记录上次选择的图片
    //    actionSheet.arrSelectedAssets = self.rememberLastSelSwitch.isOn&&self.maxSelCountTextField.text.integerValue>1 ? self.lastSelectAssets : nil;
    
    zl_weakify(self);
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {

        for (UIImage *image in images) {
            [weakSelf imageUp:image];
        }
       
    }];
    
    return actionSheet;
}
-(void)photograph{
#pragma mark - UIButton Action
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowRecordVideo =NO ;
    camera.sessionPreset = ZLCaptureSessionPreset1280x720;
    //        camera.videoType = self.configuration.exportVideoType;
    //        camera.circleProgressColor = self.configuration.bottomBtnsNormalTitleColor;
    //        camera.maxRecordDuration = self.configuration.maxRecordDuration;
    zl_weakify(self);
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        [weakSelf imageUp:image];
    };
    [self showDetailViewController:camera sender:nil];
}




-(void)accountSecurity{
    self.hidesBottomBarWhenPushed=YES;
    AccountSecurityVC *account=[[AccountSecurityVC alloc]init];
    [self.navigationController pushViewController:account animated:YES];
}
-(void)sexSelection{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:Localized(@"选择性别") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击取消");
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"男") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (![self.model.member_sex isEqualToString:@"1"]) {
            [self loadDataWithEditInfo:@"1" andKey:@"s"];
        }
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:Localized(@"女") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (![self.model.member_sex isEqualToString:@"0"]) {
            [self loadDataWithEditInfo:@"0" andKey:@"s"];
        }
    }]];
    
    [self.navigationController presentViewController:alertController animated:YES completion:nil];
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
- (NSString *)timeWithTimeIntervalString:(NSString *)timeString
{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//MARK:-GETTER
- (UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.showsVerticalScrollIndicator=NO;
        //        _myTableview.emptyDataSetSource=self;
        //        _myTableview.emptyDataSetDelegate=self;
        _tableview.scrollEnabled = YES;
    }
    return _tableview;
}
-(NSMutableArray *)titles{
    if (!_titles) {
        _titles=@[@[ Localized(@"个人头像"), Localized(@"用户名"), Localized(@"性别"), Localized(@"生日")],@[ Localized(@"账户与安全")]].copy;
    }
    return _titles;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
